﻿/**************************************************************************
创建时间:	2020/6/28 15:33:59    
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using IdentityModel;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using ZhCun.DBModel;
using ZhCun.Utils.Helpers;
using ZhCun.WebUtils.Configs;

namespace ZhCun.WebUtils.Authorizes
{
    /// <summary>
    /// 实现本地加密Token
    /// </summary>
    class LoginStateLocal : LoginStateBase
    {
        private static readonly RSAHelper _RSA;

        static LoginStateLocal()
        {
            var rsaPrivateKey = File.ReadAllText(AppContext.BaseDirectory + CommonConfig.THIS.RsaTokenKey);
            _RSA = new RSAHelper(rsaPrivateKey);
        }

        public override string CreateToken(LoginUser user)
        {
            user.ExpiresTime = DateTime.Now.Add(user.Expires);

            var str = user.ToString();
            var token = _RSA.Encrypt(str);

            //var json = JsonHelper.Serialize(user);
            //var token = _RSA.Encrypt(json);
            return token;
        }

        public override LoginUser Get(string token)
        {
            if (token.IsEmpty()) return null;
            string tokenStr;
            try
            {
                tokenStr = _RSA.Decrypt(token);
            }
            catch (Exception ex)
            {
                Utils.LogHelper.LogObj.Error("解析Token字符串异常", ex);
                return null;
            }

            var user = LoginUser.FromString(tokenStr);
            //var user = JsonHelper.Deserialize<LoginUser>(userJson);
            if (user == null) return null;

            if (user.ExpiresTime < DateTime.Now) return null;

            return user;
        }

        public override string RefreshToken(string token)
        {
            var user = Get(token);
            return CreateToken(user);
        }

        public override bool Remove(string token)
        {
            return true;
        }

        public override string Set(LoginUser user)
        {
            return CreateToken(user);
        }
    }
}